package com.ruoyi.product.service.impl;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.product.config.RabbitMQConfig;
import com.ruoyi.product.domain.JsonData;
import com.ruoyi.product.domain.ProductTask;
import com.ruoyi.product.enums.BizCodeEnum;
import com.ruoyi.product.enums.ProductOrderStateEnum;
import com.ruoyi.product.enums.StockTaskStateEnum;
import com.ruoyi.product.excepion.BizException;
import com.ruoyi.product.feign.OrderFeignSerivce;
import com.ruoyi.product.mapper.ProductTaskMapper;
import com.ruoyi.product.mq.ProductMessage;
import com.ruoyi.product.request.LockProductRequest;
import com.ruoyi.product.request.OrderItemRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.service.IProductService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 商品列表Service业务层处理
 *
 * @author 林道敬
 * @date 2025-01-02
 */
@Service
@Slf4j
public class ProductServiceImpl implements IProductService
{
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMQConfig rabbitMQConfig;
    @Autowired
    private ProductTaskMapper productTaskMapper;
    @Autowired
    private OrderFeignSerivce orderFeignSerivce;
    /**
     * 查询商品列表
     *
     * @param id 商品列表主键
     * @return 商品列表
     */
    @Override
    public Product selectProductById(String id)
    {
        return productMapper.selectProductById(id);
    }

    /**
     * 查询商品列表列表
     *
     * @param product 商品列表
     * @return 商品列表
     */
    @Override
    public List<Product> selectProductList(Product product)
    {
        return productMapper.selectProductList(product);
    }

    /**
     * 新增商品列表
     *
     * @param product 商品列表
     * @return 结果
     */
    @Override
    public int insertProduct(Product product)
    {
        product.setCreateTime(DateUtils.getNowDate());
        return productMapper.insertProduct(product);
    }

    /**
     * 修改商品列表
     *
     * @param product 商品列表
     * @return 结果
     */
    @Override
    public int updateProduct(Product product)
    {
        return productMapper.updateProduct(product);
    }

    /**
     * 批量删除商品列表
     *
     * @param ids 需要删除的商品列表主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(String[] ids)
    {
        return productMapper.deleteProductByIds(ids);
    }

    /**
     * 删除商品列表信息
     *
     * @param id 商品列表主键
     * @return 结果
     */
    @Override
    public int deleteProductById(String id)
    {
        return productMapper.deleteProductById(id);
    }

    @Override
    public List<Product> findProductsByIdBatch(List<Long> productIdList) {
        List<Product> productDOList =  productMapper.selectList(new QueryWrapper<Product>().in("id",productIdList));

        List<Product> productVOList = productDOList.stream().map(obj->beanProcess(obj)).collect(Collectors.toList());

        return productVOList;
    }

    /**
     * 锁定商品库存
     * @param lockProductRequest
     * @return
     */
    @Override
    public JsonData lockProductStock(LockProductRequest lockProductRequest) {
        String outTradeNo = lockProductRequest.getOrderOutTradeNo();
        List<OrderItemRequest> itemList  = lockProductRequest.getOrderItemList();
        //一行代码，提取对象里面的id并加入到集合里面
        List<Long> productIdList = itemList.stream().map(OrderItemRequest::getProductId).collect(Collectors.toList());
        //批量查询
        List<Product> productVOList = this.findProductsByIdBatch(productIdList);
        //分组
        Map<String,Product> productMap = productVOList.stream().collect(Collectors.toMap(Product::getId, Function.identity()));
        System.out.println("productMap :"+ productMap);

        for(OrderItemRequest item:itemList){
            //锁定商品记录
            int rows = productMapper.lockProductStock(item.getProductId(),item.getBuyNum());
            if(rows != 1){
                throw new BizException(BizCodeEnum.ORDER_CONFIRM_LOCK_PRODUCT_FAIL);
            }else {
                //插入商品product_task
                Product productVO = productMap.get(String.valueOf(item.getProductId()));
                System.out.println("item.getProductId() :"+item.getProductId());
                System.out.println("productVO :"+productVO);
                ProductTask productTaskDO = new ProductTask();
                productTaskDO.setBuyNum((long) item.getBuyNum());
                productTaskDO.setLockState(StockTaskStateEnum.LOCK.name());
                productTaskDO.setProductId(item.getProductId());
                productTaskDO.setProductName(productVO.getTitle());
                productTaskDO.setOutTradeNo(outTradeNo);
                productTaskMapper.insert(productTaskDO);
                log.info("商品库存锁定-插入商品product_task成功:{}",productTaskDO);

                // 发送MQ延迟消息，介绍商品库存
                ProductMessage productMessage = new ProductMessage();
                productMessage.setOutTradeNo(outTradeNo);
                productMessage.setTaskId(productTaskDO.getId());

                rabbitTemplate.convertAndSend(rabbitMQConfig.getEventExchange(),rabbitMQConfig.getStockReleaseDelayRoutingKey(),productMessage);
                log.info("商品库存锁定信息延迟消息发送成功:{}",productMessage);

            }

        }
        return JsonData.buildSuccess();
    }

    @Override
    public boolean releaseProductStock(ProductMessage productMessage) {
        //查询工作单状态
        ProductTask taskDO = productTaskMapper.selectOne(new QueryWrapper<ProductTask>().eq("id",productMessage.getTaskId()));
        if(taskDO == null){
            log.warn("工作单不存在，消息体为:{}",productMessage);
        }

        //lock状态才处理
        if(taskDO.getLockState().equalsIgnoreCase(StockTaskStateEnum.LOCK.name())){
            //查询订单状态
            JsonData jsonData = orderFeignSerivce.queryProductOrderState(productMessage.getOutTradeNo());

            if(jsonData.getCode() == 0){

                String state = jsonData.getData().toString();

                if(ProductOrderStateEnum.NEW.name().equalsIgnoreCase(state)){
                    //状态是NEW新建状态，则返回给消息队，列重新投递
                    log.warn("订单状态是NEW,返回给消息队列，重新投递:{}",productMessage);
                    return false;
                }

                //如果是已经支付
                if(ProductOrderStateEnum.PAY.name().equalsIgnoreCase(state)){
                    //如果已经支付，修改task状态为finish
                    taskDO.setLockState(StockTaskStateEnum.FINISH.name());
                    productTaskMapper.update(taskDO,new QueryWrapper<ProductTask>().eq("id",productMessage.getTaskId()));
                    log.info("订单已经支付，修改库存锁定工作单FINISH状态:{}",productMessage);
                    return true;
                }
            }

            //订单不存在，或者订单被取消，确认消息,修改task状态为CANCEL,恢复优惠券使用记录为NEW
            log.warn("订单不存在，或者订单被取消，确认消息,修改task状态为CANCEL,恢复商品库存,message:{}",productMessage);
            taskDO.setLockState(StockTaskStateEnum.CANCEL.name());
            productTaskMapper.update(taskDO,new QueryWrapper<ProductTask>().eq("id",productMessage.getTaskId()));


            //恢复商品库存，集锁定库存的值减去当前购买的值
            productMapper.unlockProductStock(taskDO.getProductId(),taskDO.getBuyNum().intValue());

            return true;

        } else {
            log.warn("工作单状态不是LOCK,state={},消息体={}",taskDO.getLockState(),productMessage);
            return true;
        }
    }

    private Product beanProcess(Product product) {
        product.setStock( product.getStock() - product.getLockStock());
        if(product.getStock() <= 0){
            throw new BizException(BizCodeEnum.ADD_CART_FAIL);
        }
        return product;
    }
}
